<template>
    <el-dialog model-value="dialogVisible" :title="dialogTitle" width="30%" @close="handleClose">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="学工号" prop="teacher_id">
                <el-input v-model="form.teacher_id" :disabled="form.teacher_id == -1 ?
        false : 'disabled'"  />
                <el-alert v-if="form.teacher_id" title="默认初始密码：123456" :closable="false" style="line-height: 10px;"
                    type="success">
                </el-alert>
            </el-form-item>
            <el-form-item label="姓名" prop="teacher_name">
                <el-input v-model="form.teacher_name" />
            </el-form-item>
            <el-form-item label="性别" prop="teacher_gender">
                <el-input v-model="form.teacher_gender" />
            </el-form-item>
            <el-form-item label="导师简介" prop="teacher_introduction">
                <el-input v-model="form.teacher_introduction" type="textarea" :rows="4" />
            </el-form-item>
            <el-form-item label="职称" prop="teacher_title">
                <el-input v-model="form.teacher_title" />
            </el-form-item>
            <el-form-item label="招生领域" prop="teacher_field">
                <el-input v-model="form.teacher_field" />
            </el-form-item>
            <el-form-item label="研究方向" prop="teacher_direction">
                <el-input v-model="form.teacher_direction" />
            </el-form-item>
            <el-form-item label="学历" prop="teacher_education">
                <el-input v-model="form.teacher_education" />
            </el-form-item>
            <el-form-item label="类型（博/硕导）" prop="teacher_dorm">
                <el-input v-model="form.teacher_dorm" />
            </el-form-item>
            <el-form-item v-if="user.username == '101'" label="专硕名额" prop="teacher_quota_M">
                <el-input-number  :min="0" v-model="form.teacher_quota_M" />
            </el-form-item>
            <el-form-item v-if="user.username == '101'" label="学硕名额" prop="teacher_quota_P">
                <el-input-number  :min="0" v-model="form.teacher_quota_P" />
            </el-form-item>
            <el-form-item label="研究项目" prop="teacher_project">
                <el-input v-model="form.teacher_project" type="textarea" :rows="4" />
            </el-form-item>
            <el-form-item label="获得荣誉" prop="teacher_honor">
                <el-input v-model="form.teacher_honor" type="textarea" :rows="4" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="handleConfirm">确认</el-button>
                <el-button @click="handleClose">取消</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup>
import { defineEmits, defineProps, ref, watch } from "vue";
import { toast } from '@/util/util'

// api
import {getTeaItem,saveTea} from "@/api/stu_teacher"

// 登录信息
const user = ref({})
user.value = JSON.parse(sessionStorage.getItem("currentUser"))

const props = defineProps(
    {
        teacher_id: {
            type: String,
            default: -1,
            required: true
        },
        dialogTitle: {
            type: String,
            default: '',
            required: true
        },
        dialogVisible: {
            type: Boolean,
            default: false,
            required: true
        }
    }
)
const form = ref({
    teacher_id: -1, // 学工号
    teacher_name: "", // 姓名
    teacher_gender: '',   // 性别
    teacher_introduction: "",  //导师简介
    teacher_title: "",  // 职称
    teacher_direction: "",  // 研究方向
    teacher_education: "",   // 学历
    teacher_phone: "", // 联系方式
    teacher_dorm: "", // 类型（博/硕导）
    teacher_quota_M: 0,  // 专硕名额
    teacher_quota_P: 0, // 学硕名额
    teacher_project: "", //  研究项目
    teacher_honor: "",  // 获得荣誉
    teacher_field: "",  // 招生领域
})

// 定义身份证号验证规则
const validateIdCard = async (rule, value, callback) => {
  const reg = /(^\d{15}$)|(^\d{17}([0-9]|X|x)$)/;
  if (!value) {
    callback(new Error('请输入身份证号'));
  } else if (!reg.test(value)) {
    callback(new Error('请输入正确的身份证号'));
  } else {
    // 18位身份证号校验码验证
    if (value.length === 18) {
      const idCardWi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; // 加权因子
      const idCardY = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2]; // 校验码对应值
      let sum = 0;
      for (let i = 0; i < 17; i++) {
        sum += parseInt(value.charAt(i), 10) * idCardWi[i];
      }
      const lastChar = idCardY[sum % 11].toString().toUpperCase();
      if (value.charAt(17).toUpperCase()!== lastChar) {
        callback(new Error('请输入正确的身份证号！'));
      } else {

        // 检验成功之后-检验是否存在
        if (form.value.teacher_id == -1) {
        const res = await getTeaItem({
            teacher_id:form.value.teacher_id,
        }) 
        if (res.data.code == 500) {
            callback(new Error("该工号已存在！"));
        } else {
            callback();
        }
    } else {
        callback();
    }
      }
    } else {
      callback();
    }
  }
};

const rules = ref({
    teacher_id: [
        { required: true, message: '请输入学工号' },
    ],
    teacher_name: [
        { required: true, message: '请输入姓名' ,trigger: "blur"},
    ],
    teacher_title: [
        { required: true, message: '请输入职称' ,trigger: "blur"},
    ],
    teacher_dorm: [
        { required: true, message: '请输入类型（博/硕导）' ,trigger: "blur"},
    ],
    teacher_phone: [{ required: true, message: "联系方式不能为空", trigger: "blur" }, {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: "blur"
    }],
})

const formRef = ref(null)
const initFormData = async (teacher_id) => {
    const res = await getTeaItem({
            teacher_id:teacher_id,
        }) 
    form.value = res.data.tea;
}
watch(
    () => props.dialogVisible,
    () => {
        let teacher_id = props.teacher_id;
        if (teacher_id != -1) {
            initFormData(teacher_id)
        } else {
            form.value = {
                teacher_id: -1, // 学工号
                teacher_name: "", // 姓名
                teacher_gender: '',   // 性别
                teacher_introduction: "",  //导师简介
                teacher_title: "",  // 职称
                teacher_direction: "",  // 研究方向
                teacher_education: "",   // 学历
                teacher_phone: "", // 联系方式
                teacher_dorm: "", // 类型（博/硕导）
                teacher_quota_M: 0,  // 专硕名额
                teacher_quota_P: 0, // 学硕名额
                teacher_project: "", //  研究项目
                teacher_honor: "",  // 获得荣誉
                teacher_field: "",  // 招生领域
            }
        }
    }
)
const emits = defineEmits(['update:modelValue', 'initTeaList'])
const handleClose = () => {
    emits('update:modelValue', false)
}
const handleConfirm = () => {
    formRef.value.validate(async (valid) => {
        if (valid) {
            let result = await saveTea(form.value)
            let data = result.data;
            if (data.code == 200) {
                toast("执行成功！")
                formRef.value.resetFields();
                emits("initTeaList")
                handleClose();
            } else {
                toast(data.msg,'error')
            }
        } else {
            console.log("fail")
        }
    })
}
</script>
<style scoped>
</style>